

import UIKit
import AFNetworking
//  定义请求类型的枚举, 默认值从0开始
enum RequestType: Int {
    case GET
    case POST
}

//  网络请求工具类
class CZNetworkTools: AFHTTPSessionManager {
    //  单例全局访问点
    static let sharedToos: CZNetworkTools = {
        let tools = CZNetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    //  封装get/post请求
    func request(type: RequestType, url: String, params: AnyObject?, callBack: (response: AnyObject?, error: NSError?)->()) {
        
        if type == .GET {
            GET(url, parameters: params, progress: nil, success: { (_, response) -> Void in
                
                callBack(response: response, error: nil)
                
                }, failure: { (_, error) -> Void in
                    callBack(response: nil, error: error)
            })
        } else {
            POST(url, parameters: params, progress: nil, success: { (_, response) -> Void in
                callBack(response: response, error: nil)
                }, failure: { (_, error) -> Void in
                    callBack(response: nil, error: error)
            })
        }
    }
}

//微博首页接口
extension CZNetworkTools {
       // 获取微博数据
    func loadStatus(callBack: (response: AnyObject?,error: NSError?) -> ()) {
        //  准备接口地址
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        //准备参数
        let params = [
           "access_token": CZUserAccountViewModel.shareUserAccount.accessToken!
         ]
        
        print(url + "?access_token=" + CZUserAccountViewModel.shareUserAccount.accessToken!)
        
        //get请求
        request(.GET, url: url, params: params, callBack: callBack)
    }  
}




//  OAuth登录相关接口
extension CZNetworkTools {
    //  通过授权码(code)获取accesstoken
    func requestAccesstoken(code: String, callBack: (response: AnyObject?, error: NSError?) -> ()) {
        //  准备接口地址
        let url = "https://api.weibo.com/oauth2/access_token"
        //  准备参数
        let params = [
            "client_id": WeiboAppKey,
            "client_secret": WeiboAppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WeiboRedirect_Uri
        ]
        
        //  使用通用接口去请求
        request(.POST, url: url, params: params, callBack: callBack)
        
        
        
    }
    
    
    //  获取用户信息
    func requestUserInfo(userAccount: CZUserAccount, callBack: (response: AnyObject?, error: NSError?) -> ()) {
        //  请求接口地址
        let url = "https://api.weibo.com/2/users/show.json"
        //  准备请求参数
        //  int64,跟字符串放在一起编译不通过,需要转换成字符串
        let params = [
            "access_token": userAccount.access_token!,
            "uid": "\(userAccount.uid)"
        ]
        
        request(.GET, url: url, params: params, callBack: callBack)
    }

}



















